package com.suxin.netty.remoting;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Tang
 * @classname NettyRemotingServer
 * @description [  ]
 * @date 2022/12/8 23:24
 */
@Slf4j
public class NettyRemotingServer extends AbstractNettyRemoting implements RemotingServer {

    public static void main(String[] args) {
        NettyRemotingServer server = new NettyRemotingServer(new NettyServerConfig());
        server.start();
    }

    private EventLoopGroup eventLoopGroupSelector;
    private EventLoopGroup eventLoopGroupBoss;
    private ServerBootstrap serverBootstrap;

    private ChannelEventListener listener;
    private NettyServerConfig config;
    private NettyEncoder nettyEncoder;

    private int port;

    public NettyRemotingServer(NettyServerConfig config) {
        this(config, null);
    }

    public NettyRemotingServer(NettyServerConfig config, ChannelEventListener listener) {
        this.config = config;
        this.listener = listener;
        this.serverBootstrap = new ServerBootstrap();
        int publicThreadNums = config.getServerCallbackExecutorThreads();
        this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
            private final AtomicInteger threadIndex = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "NettyServerPublicExecutor_" + this.threadIndex.incrementAndGet());
            }
        });

        this.eventLoopGroupSelector = new NioEventLoopGroup(config.getServerSelectorThreads(), new ThreadFactory() {
            private final AtomicInteger threadIndex = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, String.format("NettyServerNIOSelector_%d", this.threadIndex.incrementAndGet()));
            }
        });

        this.eventLoopGroupBoss = new NioEventLoopGroup(1, new ThreadFactory() {
            private final AtomicInteger threadIndex = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, String.format("NettyNIOBoss_%d", this.threadIndex.incrementAndGet()));
            }
        });

    }


    @Override
    public void start() {
        this.nettyEncoder = new NettyEncoder();
        this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, false)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_SNDBUF, this.config.getServerSocketSndBufSize())
                .childOption(ChannelOption.SO_RCVBUF, this.config.getServerSocketRcvBufSize())
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(NettyRemotingServer.this.nettyEncoder)
                                .addLast(new NettyDecoder())
                                .addLast(new IdleStateHandler(5, 5, 10, TimeUnit.SECONDS))
                                .addLast(new NettyServerHandler(NettyRemotingServer.this))
                        ;
                    }
                });

        ChannelFuture sync = null;
        try {
            sync = this.serverBootstrap.bind(this.config.getListenPort()).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        InetSocketAddress socketAddress = (InetSocketAddress) sync.channel().localAddress();
        this.port = socketAddress.getPort();
        log.info("start server...{}",this.port);
    }

    @Override
    public void shutdown() {
        this.eventLoopGroupSelector.shutdownGracefully();
        this.eventLoopGroupBoss.shutdownGracefully();
        this.publicExecutor.shutdown();
    }

    @Override
    public RemotingCommand invokeSync(RemotingCommand request, long timeoutMillis) {
        return null;
    }

    @Override
    public RemotingCommand invokeAsync(RemotingCommand request, long timeoutMillis, InvokeCallback callback) {
        return null;
    }
}
